package server.webEE.bean;

import java.math.BigInteger;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import test.bean.TestSessionLessBean;
import test.bean.TestSessionLessHomeLocal;
import weblogic.logging.NonCatalogLogger;

public class TestMessageBean implements MessageListener, MessageDrivenBean {
	private static final NonCatalogLogger NON_CATALOG_LOGGER = new NonCatalogLogger(
			TestMessageBean.class.getName());

	/**
	 * 
	 */
	private static final long serialVersionUID = -4610852732765427104L;

	private MessageDrivenContext messageDrivenContext;
	private Context context;

	private Object refSession;
	private TestSessionLessHomeLocal sessionHomeLocal;
	private TestSessionLessBean lessBean;
	
	public void ejbCreate(){
		NON_CATALOG_LOGGER.error("ejbCreate");
		try {
			refSession = context
					.lookup("test/TestSessionLess");
			sessionHomeLocal = (TestSessionLessHomeLocal) PortableRemoteObject
					.narrow(refSession, TestSessionLessHomeLocal.class);
			lessBean = (TestSessionLessBean) sessionHomeLocal
					.create();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CreateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void ejbRemove() throws EJBException {
		try {
			NON_CATALOG_LOGGER.error("ejbRemove");
			this.context.close();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			this.messageDrivenContext = null;
		}
	}

	@Override
	public void setMessageDrivenContext(MessageDrivenContext arg0)
			throws EJBException {
		NON_CATALOG_LOGGER.error("setMessageDrivenContext");
		this.messageDrivenContext = arg0;
		try {
			context = new InitialContext();
		} catch (NamingException e) {
			NON_CATALOG_LOGGER.error(e.getMessage(), e);
		}
	}

	@Override
	public void onMessage(Message arg0) {
		NON_CATALOG_LOGGER.error("onMessage");
		try {
			MapMessage mapMessage = (MapMessage) arg0;
			BigInteger id = (BigInteger) mapMessage.getObject("ID");


			lessBean.monitoring(id);
		} catch (ClassCastException cce) {
			NON_CATALOG_LOGGER.error(cce.getMessage(), cce);
		} catch (JMSException e) {
			NON_CATALOG_LOGGER.error(e.getMessage(), e);
		}
	}

}
